﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;



namespace fluke45_viewer_txy.DataAnalysis
{
    class dataAnalysis
    {
        //声明坐标点存储结构
        public ArrayList PointValueArray;
        //声明相关结果参数
        public double k_para;
        public double b_para;
        public double r2_para;  //线性拟合的相关参数y = ax + b,相关度r^2


        public dataAnalysis()
        {
            PointValueArray = new ArrayList();
            k_para = 0;
            b_para = 0;
            r2_para = 0;
        }

        


        private void leastSqure(ArrayList Points)
        {
            double sumX = 0;
            double sumY = 0;
            double sumXY = 0;
            double sumX2 = 0;
            k_para = 0;
            b_para = 0;
            foreach (PointValue point in Points)
            {

                sumX += point.X;
                sumY += point.Y;
                sumXY += point.X * point.Y;
                sumX2 += point.X * point.X;
            }
            k_para = (Points.Count * sumXY - sumX * sumY) / (Points.Count * sumX2 - sumX * sumX);
            b_para = (sumX2 * sumY - sumX * sumXY) / (Points.Count * sumX2 - sumX * sumX);
        }

        public bool analysExistingData()
        {
            if (PointValueArray.Count == 0)
                return false;   //数组为空，返回失败
            //计算相关参数
            leastSqure(this.PointValueArray);
            return true;
        }

        /// <summary>
        /// 向集合中添加坐标点
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        public void addPoint(double x, double y)
        {
            PointValue point = new PointValue();
            point.X = x;
            point.Y = y;
            this.PointValueArray.Add(point);
        }

        /// <summary>
        /// 清空坐标记录集合
        /// </summary>
        public void cleanArray()
        {
            this.PointValueArray.Clear();
        }

        public ArrayList getPointValueArray()
        {
            if(this.PointValueArray != null)
                return this.PointValueArray;
            else
                return new ArrayList();
        }
    }
}
